package com.xiaohao.communication.ESutils;

import lombok.extern.java.Log;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 高亮配置器
 */
@Log
@Component
public class HighlightProcessor {

    public HighlightBuilder allFieldHighlightBuilder() {
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        HighlightBuilder.Field highlightTitle =
                new HighlightBuilder.Field("*");
        highlightTitle.highlighterType("unified");
        highlightBuilder.field(highlightTitle);
        return highlightBuilder;
    }

    public HighlightBuilder singleFieldHighlightBuilder(String field) {
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        HighlightBuilder.Field highlightTitle =
                new HighlightBuilder.Field(field);
        highlightTitle.highlighterType("unified");
        highlightBuilder.field(highlightTitle);
        return highlightBuilder;
    }

    public HighlightBuilder mutiFieldHighlightBuilder(String... fields) {
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        for (String field : fields) {
            HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field(field);
            highlightTitle.highlighterType("unified");
            highlightBuilder.field(highlightTitle);
        }
        return highlightBuilder;
    }

    public void highlightProcessor(SearchHits hits) {
        for (SearchHit hit : hits.getHits()) {
            try {
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField highlight = highlightFields.get("*");
                Text[] fragments = highlight.fragments();
                String fragmentString = fragments[0].string();
            } catch (NullPointerException e) {
                //e.printStackTrace();
                log.warning("found null in result set");
                continue;
            }
        }
    }
}
